package com.admin.service.export.impl;

import com.admin.common.enums.FileZipModelEnum;
import com.admin.common.exception.BizException;
import com.admin.common.util.FileZipUtil;
import com.admin.domain.Attachment;
import com.admin.service.AttachmentService;
import com.admin.service.export.ExportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author: weiyang
 * @Date: 2022/07/08/10:27
 * @Description:
 */
@Service
@Slf4j
public class ExportServiceImpl implements ExportService {

    @Value("${attachment.uploadPath}")
    private String FILE_UPLOAD_PATH;

    @Value("${attachment.prefix}")
    private String FILE_URL;

    @Value("${attachment.zipModel:downLoad}")
    private String FILE_ZIP_MODEL;

    @Autowired
    private AttachmentService attachmentService;

    @Override
    public String exportAttachment(Integer declareId) {
        List<Integer> declareIdList = new ArrayList<>();
        declareIdList.add(declareId);
        List<Attachment> attachmentList = attachmentService.findListByDeclareIds(declareIdList);
        if (CollectionUtils.isEmpty(attachmentList)) {
            throw new BizException(-1, "暂无附件可下载");
        }

        List<String> attachmentUrl = attachmentList.stream().map(Attachment::getAttachPath).collect(Collectors.toList());
        try {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy");
            String yearDirectory = dateTimeFormatter.format(LocalDateTime.now());

            dateTimeFormatter = DateTimeFormatter.ofPattern("MM");
            String monthDirectory = dateTimeFormatter.format(LocalDateTime.now());

            //3、目录不存在，动态创建
            String zipFileStoreDir = FILE_UPLOAD_PATH + yearDirectory + File.separator + monthDirectory;
            File directory = new File(zipFileStoreDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            String fileName = UUID.randomUUID() + "attachment.zip";
            String zipFileStorePath = zipFileStoreDir + File.separator + fileName;// 文件名

            boolean isSuccess = false;
            if (Objects.equals(FileZipModelEnum.DOWN_LOAD.getName(), FILE_ZIP_MODEL)) {
                isSuccess = FileZipUtil.fileDownZip(attachmentUrl, zipFileStorePath);
            } else {
                attachmentUrl = attachmentUrl.stream().map(t -> {
                    return t.replace(FILE_URL, FILE_UPLOAD_PATH);
                }).collect(Collectors.toList());
                isSuccess = FileZipUtil.fileCopyZip(attachmentUrl, zipFileStorePath);
            }

            if (!isSuccess) {
                throw new BizException(-1, "附件导出失败");
            }

            return FILE_URL + yearDirectory +File.separator + monthDirectory + File.separator + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
